package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AdminAuthorizingRealm  extends AuthorizingRealm {

    @Autowired
    AdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    //获取权限信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        DtsAdmin admin = (DtsAdmin) getAvailablePrincipal(principals);
        Integer[] roleIds = admin.getRoleIds();
        //查询角色字符串集合
        Set<String> roles =roleService.findRolesByRoleIds(roleIds);


        //查询权限字符串集合
        Set<String> perms =permissionService.findPermsByRoleIds(roleIds);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);


        return authorizationInfo;
    }

    //获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的账号和密码
        String username = (String) token.getPrincipal();
        String password  = new String((char[])token.getCredentials());

        //根据用户名获取 用户(管理员)信息
        DtsAdmin admin  = adminService.findByUsername(username);
        if(admin == null){
            throw new UnknownAccountException("未知的用户名");
        }

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        if(password == null || !passwordEncoder.matches(password, admin.getPassword())){
            throw new CredentialsException("密码错误");
        }

        if(admin.getDeleted()){
            throw new LockedAccountException("账户已锁定");
        }

        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, password, admin.getUsername());

        return authenticationInfo;
    }
}
